package com.bw.jetpacktest.live;

import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 依托原有LiveData处理掉多个观察者观察livedata时数据倒灌问题
 * */
public class LiveDataBus<T> extends MutableLiveData<T> {
    private AtomicBoolean flag = new AtomicBoolean(false);
    //具有原子性得Boolean值，多线程中使用，保证在多线程得情况下只有一个线程可以操作AtomicBoolean值

    @Override
    public void observe(@NonNull LifecycleOwner owner, @NonNull final Observer<? super T> observer) {
        super.observe(owner, new Observer<T>() {
            @Override
            public void onChanged(T t) {
                //compareAndSet(boolean,boolean)目标值,更新值:原有值与目标值比对如相同更新boolean
               if (flag.compareAndSet(true,false)){
                    observer.onChanged(t);
               }
            }
        });
    }

    @Override
    public void setValue(T value) {
        flag.set(true);//添加过数据
        super.setValue(value);
    }
}
